package com.ruoyi.quartz.util;

import com.github.tusharepro.core.TusharePro;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;

public class TushareUtil {

  public static TusharePro.Builder getBuilder() {
    final OkHttpClient defaultHttpClient =
        new OkHttpClient.Builder()
            .addInterceptor(
                new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE))
            .build();
    return new TusharePro.Builder()
        .setToken("879662431d7b5123d4fc7da03760e4025c499c4457a4e514bf5e5c5a")
        .copy() // 将配置拷贝
        .setMaxRetries(5) // 设置重试次数, 默认为3
        .setRetrySleepTimeUnit(TimeUnit.SECONDS) // 设置重试sleep单位, 默认毫秒
        .setRetrySleepTimeOut(60L) // 设置重试sleep时间, 默认为0
        .setRequestExecutor(
            Executors.newSingleThreadExecutor(
                (r -> {
                  Thread thread = new Thread(r);
                  thread.setDaemon(true);
                  return thread;
                }))) // 设置请求线程池, 默认CachedThreadPool
        .setHttpFunction(
            requestBytes -> { // requestBytes -> function -> responseBytes
              try {
                okhttp3.Request request =
                    new okhttp3.Request.Builder()
                        .url("http://api.tushare.pro")
                        .post(
                            RequestBody.create(
                                MediaType.parse("application/json; charset=utf-8"), requestBytes))
                        .build();

                return defaultHttpClient.newCall(request).execute().body().bytes();
              } catch (IOException e) {
                e.printStackTrace();
              }
              return null;
            });
  }
}
